import React from 'react'
import {Row, Col, Input, Button, Table, Modal, message} from 'antd'
import axios from 'axios'
import api from '../../../api/api'
import '../styles.css'
import Addcompany from "./Addcompany"

const {Search} = Input;


class CompanyManagement extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            modelData: {
                title: "新增公司",
                visible: false,
                type: 1,//新增公司:1,编辑: 2,新增子公司:3
                gridList: {}
            },
            companyList: [],//公司列表数据
            companyInfo: "",
            pageNum: 1,
            pageSize: 10,
            total: 0
        }
    }

    columns = [
        {
            title: '企业ID',
            dataIndex: 'companyId',
            key: 'companyId',
            width: '20%'
        },
        {
            title: '企业名称',
            dataIndex: 'companyName',
            key: 'companyName',
            width: '30%'
        },
        {
            title: '账号',
            dataIndex: 'account',
            width: '10%',
            key: 'account'
        },
        {
            title: '更新时间',
            dataIndex: 'createTime',
            width: '20%',
            key: 'createTime'
        },
        {
            title: '操作',
            dataIndex: 'option',
            width: '20%',
            key: 'option',
            render: (text, record, index) => {
                return (
                    <span>
            <a className="optionMargin" onClick={() => this.onClickAdd(record)}>添加子公司</a>
            <a className="optionMargin" onClick={() => this.onClickEdit(record)}>编辑</a>
            <a className="optionMargin" onClick={() => this.onClickDelete(record.companyId)}>删除</a>
          </span>
                )
            }
        }
    ]
    onRef = (ref) => {
        this.child = ref
    }

    componentDidMount() {
        this.getCompanyList();
    }

    getParam(value) {
        this.setState({companyInfo: value}, () => {
            this.getCompanyList()
        });
    }

    getCompanyList() {
        const that = this;
        var param = {};
        param.companyName = that.state.companyInfo
        param.orgCode = localStorage.getItem("orgCode")
        let url = api.api_URL + "/admin/company/queryCompanyInfoByParamAndPage?pageNum=" + this.state.pageNum + "&pageSize=" + this.state.pageSize;
        axios({
            method: 'POST',
            url: url,
            data: JSON.stringify(param),
            headers: {
                "Authorization": localStorage.getItem('token'),
                "Content-Type": "application/json;charset=UTF-8"
            },
        }).then(function (response) {
            let data = response.data.data.list;
            that.setState({
                companyList: data.content,
                total: data.totalSize
            })
        }).catch(function (error) {
            console.log(error);
            message.error({content:"加载失败,请重新尝试！"})
        })
    }

    //分页操作
    onBaseClick(current, pageSize) {
        this.setState({
            pageNum: current,
            pageSize: pageSize
        }, () => {
            this.getCompanyList()
        });
    }

    //添加
    onClickAdd(item) {
        this.setState({
            modelData: {
                title: "新增子公司",
                type: 3,
                visible: true,
                gridList: item
            }
        }, () => {
            this.child.clearData()
        });
    }

    //编辑
    onClickEdit(item) {
        this.setState({
            modelData: {
                title: "编辑",
                type: 2,
                visible: true,
                gridList: item
            }
        }, () => {
            this.child.initEditData()
        });
    }

    //删除
    onClickDelete(item) {
        let that = this;
        let configModel = Modal.confirm({
            title: '删除',
            content: '是否确认删除？',
            onOk: (values) => {
                return new Promise((res, rej) => {
                    let url = api.api_URL + "/admin/company/deleteCompanyInfo?companyId=" + item;
                    axios({
                        method: 'POST',
                        url: url,
                        headers: {
                            "Authorization": localStorage.getItem('token'),
                            "Content-Type": "application/json;charset=UTF-8"
                        },
                    }).then(function (response) {
                        message.success({content:"删除成功！"})
                        that.getCompanyList()
                        configModel.destroy();
                    })
                        .catch(function (error) {
                            message.error({content:"删除失败，请重新尝试！"})
                            console.log(error);
                        })
                }).catch((e) => console.warn(e));
            },
            onCancel() {
            },
        })
    }

    //新增
    addcompany() {
        this.setState({
            modelData: {
                title: "新增公司",
                type: 1,
                visible: true
            }
        }, () => {
            this.child.clearData()
        });
    }

    handleOk = e => {
        console.log(e);
        this.setState({
            modelData: {
                visible: false
            },
        });
    }
    handleCancel = e => {
        this.setState({
            modelData: {
                visible: false
            },
        }, () => {
            this.refresh()
        });
    }

    refresh() {
        this.getCompanyList()
    }

    render() {
        return (
            <div className="girdBg">
                <Row className="searchBox">
                    <Col span={6}>
                        <Search style={{width: 200}}
                                placeholder="请输入"
                                onSearch={value => this.getParam(value)}
                                 allowClear
                        />
                    </Col>
                    <Col icon={"save"} span={18} className="btnRight">
                        <Button type='primary' onClick={this.addcompany.bind(this)}>新增公司</Button>
                        {/*<Button shape='circle' type='primary' icon="download"/>*/}
                    </Col>
                </Row>
                <Row style={{margin: 30}}>
                    <Table
                        columns={this.columns}
                        dataSource={this.state.companyList}
                        scroll={{x: 'max-content'}} // 加上这条  横向滚动  支持此属性的浏览器内容就不会换行了
                        columns={this.columns.map(item => { // 通过配置 给每个单元格添加不换行属性
                            const fun = () => ({style: {whiteSpace: 'nowrap'}});
                            item.onHeaderCell = fun;
                            item.onCell = fun;
                            return item;
                        })}
                        pagination={{
                            simple: false,
                            current: this.state.pageNum,
                            total: this.state.total,
                            pageSize: this.state.pageSize,
                            showTotal: (count = this.state.total) => {
                                return '共' + count + '条'
                            },
                            onChange: (current, pageSize) => {
                                this.onBaseClick(current, pageSize)
                            }
                        }}
                    />
                </Row>

                <Addcompany data={this.state.modelData} handleCancel={this.handleCancel} refresh={this.refresh}
                            onRef={this.onRef} history={this.props.history}/>
            </div>
        )
    }
}


export default CompanyManagement